package 力扣_树算法.遍历.层序遍历扩展;

import java.util.*;

/**103. 二叉树的锯齿形层序遍历
 * @author zx
 * @create 2022-04-09 16:55
 */
public class 二叉树的锯齿形层序遍历 {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(root == null){
            return res;
        }
        int flag = 1;
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            //保存当前层的元素
            Deque<Integer> level = new ArrayDeque<>();
            int levelCount = queue.size();
            for(int i = 0;i < levelCount;i++){
                TreeNode node = queue.poll();
                if(flag % 2 == 1){
                    //奇数层,从左往右遍历
                    level.offerLast(node.val);
                }else{
                    //偶数层,从右往左遍历
                    level.offerFirst(node.val);
                }
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
            }
            res.add(new ArrayList<>(level));//参考官方解法：这必须new
            flag++;
        }
        return res;
    }
}
